﻿using System;
using System.Linq;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Diagnostics;
using SoftwareLogistics.SharepointClient.Library.UserService;
using SoftwareLogistics.SharepointClient.Library;

namespace SoftwareLogistics.SharepointClient.Library.Models
{
    public class SPUsers
    {
        private const string STR_Usersdat = "users.dat";
        public event EventHandler GotUsers;
        private List<SPUser> _users;
        public IOrderedEnumerable<SPUser> Users
        {
            get{return _users.OrderBy(user=>user.ID);}
        }

        public SPUser CurrentUser {set; get;}

        public void SetCurrentUser(string userName)
        {
            CurrentUser = Users.Where(usr => usr.Name.ToLower() == userName.ToLower()).FirstOrDefault();
            if (CurrentUser == null)
                throw new Exception("Unknown current user.");

            Common.Filters = ListFilters.GetFilters();
        }

        private List<SPUser> GetUsersFromStore()
        {
            var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
            if (store.FileExists(STR_Usersdat))
            {
                using (var file = store.OpenFile(STR_Usersdat, System.IO.FileMode.Open))
                {
                    var serializer = new DataContractSerializer(typeof(List<SPUser>));
                    return serializer.ReadObject(file) as List<SPUser>;
                }
            }

            return null;
        }

        public void GetUsers()
        {
            _users = GetUsersFromStore();
            if (_users != null)
            {                 
                GotUsers(this, new GotUsersEventArgs() { Users = _users });
                return;
            }

            var userService = new UserGroupSoapClient();
            userService.CookieContainer = Common.AuthService.GetCookieJar;

            userService.GetAllUserCollectionFromWebCompleted += (sndr, args) =>
            {
                var rows = args.Result.Descendants(XName.Get("User", "http://schemas.microsoft.com/sharepoint/soap/directory/"));
                                
                _users = new List<SPUser>();

                _users.Add(new SPUser() { ID = 0, Name = "-select-" });

                foreach (var row in rows)
                {
                    var user = SPUser.Create(row);
                    if(user.ToString().ToLower() != "local service" &&
                        user.ToString().ToLower() != "system account")
                    _users.Add(user);
                }

                var store = System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();
                if(store.FileExists(STR_Usersdat))
                    store.DeleteFile(STR_Usersdat);

                using (var file = store.CreateFile(STR_Usersdat))
                {
                    var serializer = new DataContractSerializer(typeof(List<SPUser>));
                    serializer.WriteObject(file, _users);
                }

                var userEventArgs = new GotUsersEventArgs { Users = _users };
                GotUsers(this, userEventArgs);
            };

            userService.GetRolesAndPermissionsForSiteCompleted += (sndr, args) =>
                {
                    Debug.WriteLine(args.Result);
                };

            userService.GetRolesAndPermissionsForSiteAsync();
            userService.GetAllUserCollectionFromWebAsync();
        }
    }
}
